import { reactive, toRefs } from "vue"
import { onShow, onUnload, onLoad } from "@dcloudio/uni-app";
import { LoginStore } from "@/store/modules/login";
import { ConfigStore } from "@/store/modules/config.js"
const uniIdCo = uniCloud.importObject("uni-id-co", { customUI: true })
const loginApi = uniCloud.importObject('qc-login', { customUI: true })
/**
 * @description  公共登录逻辑封装
 * @param rules 表单校验规则
 * */
export const useLogin = (formRefs, captchaRef, rules) => {
	const state = reactive({
		formData: {
			username: "", //账号
			password: '', //密码
			captcha: '', //图形验证码
		},
		formItem: {
			loading: false, //防抖
			eyeShow: false, //密码显示状态
			needCaptcha: false, //显示隐藏验证码状态
		},
		uniIdRedirectUrl: '', //路由地址
		// 校验规则
		rules
	});
	onLoad((e) => {
		if (e.uniIdRedirectUrl) {
			state.uniIdRedirectUrl = decodeURIComponent(e.uniIdRedirectUrl)
		}
		// #ifdef MP-WEIXIN
		if (getCurrentPages().length === 1) {
			uni.hideHomeButton()
			console.log('已隐藏：返回首页按钮');
		}
		// #endif
	})

	// 兼容H5
	onShow(() => {
		// #ifdef H5
		document.onkeydown = event => {
			var e = event || window.event;
			if (e && e.keyCode == 13) { //回车键的键值为13
				login()
			}
		};
		// #endif
	})

	// 卸载键盘事件
	onUnload(() => {
		// #ifdef H5
		document.onkeydown = false
		// #endif
	});
	/**
	 * @description: 登录事件
	 * @param {*} formRef 表单实例
	 * @param {*} captchaRef 验证码实例
	 */
	const login = async () => {
		formRefs.value.validator(state.formData, rules).then(async res => {
			// 如果没有输入验证码并且显示的有验证码输入提示 就提示输入验证码
			if (state.formData.captcha.length != 4 && state.formItem.needCaptcha) {
				// 让验证码输入框获取焦点
				captchaRef.value.focusCaptchaInput = true
				return uni.showToast({
					title: '请输入验证码',
					icon: 'none',
					duration: 3000
				});
			}
			if (!res.isPassed) return
			uni.showLoading({
				title: '登录中',
				mask: true
			});
			const cid = uni.getStorageSync('getui_cid');
			const { boundNum } = ConfigStore().getConfig
			// 登录前，查询该设备是否绑定了多个账号
			// 首先通过用户的手机号，查询出用户的id，然后查询一下用户是否有设备id,没有的话就添加，有的话，就对比
			if (boundNum !== 0) {
				const { data } = await loginApi.getDevice({ mobile: state.formData.username })
				if (data !== null) {
					// 先去重，查询获取到的设备id里包含不包含，当前的设备id,如果包含那就不添加了，否则就添加
					if (!data?.device_id?.includes(cid) && data?.device_id?.length < boundNum) {
						await loginApi.addDevice({ user_id: data.uid, device_id: [cid] })
					}
				}
				if (data && data?.device_id?.length >= boundNum && !data?.device_id.includes(cid)) {
					return uni.fui.toast('该账号已绑定多个设备请切换原设备登录')
				}
			}
			// 如果校验通过直接提交注册
			submitForm(captchaRef)
		}).catch((errors) => {
			console.log(errors);
		})
	}

	/**
	 * @description: 登录接口
	 * @param {*} captchaRef 验证码实例
	 */
	const submitForm = async (captchaRef) => {
		try {
			let data = {
				password: state.formData.password,
				captcha: state.formData.captcha
			}
			// 判断是什么登录方式
			if (/^1\d{10}$/.test(state.formData.username)) {
				data.mobile = state.formData.username
			} else if (/@/.test(state.formData.username)) {
				data.email = state.formData.username
			} else {
				data.username = state.formData.username
			}
			// 调用登录接口
			const res = await uniIdCo.login(data)
			const cid = uni.getStorageSync('getui_cid');
			// 每次登录前，先把用户的设备id,存入数据表，然后每次登录新设备的时候，把上一个账号给下线了
			if (uni.getPushClientId) {
				uni.getPushClientId({
					success: async function(e) {
						const pushClientId = e.cid
						await loginApi.loginOffline({ mobile: state.formData.username, push_id: pushClientId })
					},
					fail(e) {
						console.log(e)
					}
				})
			} else {
				await loginApi.loginOffline({ mobile: state.formData.username, push_id: cid })
			}
			// 用于登录成功时需要配置的逻辑（如存储信息，记录设备，记录登录日志）
			const LoginState = LoginStore()
			LoginState.loginSuccess({ ...res, toastText: '登录成功', uniIdRedirectUrl: state.uniIdRedirectUrl })
			// 登录成功后跳转对应页面
			if (!state.uniIdRedirectUrl) {
				uni.switchTab({
					url: '/pages/tabbar/index/index'
				})
			}

		} catch (e) {
			console.log(e.errCode);
			console.log(e.errMsg);
			// 如果输入密码输入错误多次 就提示图形验证码
			if (e.errCode == 'uni-id-captcha-required') {
				state.formItem.needCaptcha = true
			} else if (state.formItem.needCaptcha) {
				//登录失败，自动重新获取验证码
				captchaRef.value.getImageCaptcha()
			}
			uni.fui.toast(e.errMsg)
			// uni.showModal({
			//     title: '提示',
			//     content: e.errMsg || `登录失败: ${e.errCode}`,
			//     // content:`登录失败: ${e.errCode}`,
			//     showCancel: false
			// })

		}
	}

	// 去注册
	const toRegister = () => {
		uni.navigateTo({
			url: '/pages/register/register'
		});
	}
	// 忘记密码
	const amend = () => {
		uni.navigateTo({
			url: '/pages/entrance/amend/amend'
		});
	}

	return {
		...toRefs(state),
		login,
		toRegister,
		amend,
	};
};